package com.xihua.sx.service.impl;

import com.xihua.sx.mapper.UserMapper;
import com.xihua.sx.pojo.EditPassword;
import com.xihua.sx.pojo.User;
import com.xihua.sx.service.UserService;
import com.xihua.sx.utils.ResponseMessage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jws.Oneway;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseMessage login(String username, String password) {
        User user = userMapper.login(username, password);
        if (user == null){
            return new ResponseMessage(500,"登陆失败");
        }
        redisTemplate.opsForValue().set(username,user);
        return new ResponseMessage(200,"登录成功",user);
    }

    @Override
    public ResponseMessage editPassword(EditPassword editPassword) {
        System.out.println("editPasswprd:"+editPassword.toString());
        User user = (User) redisTemplate.opsForValue().get(editPassword.getUsername());
        System.out.println("user:"+user);
        if (!user.getPassword().equals(editPassword.getOldPassword())){
            return new ResponseMessage(500,"旧密码错误");
        }
        User newUser = new User();
        newUser.setUserId(user.getUserId());
        newUser.setUsername(user.getUsername());
        newUser.setPassword(editPassword.getNewPassword());
        int i = userMapper.updateById(newUser);
        redisTemplate.opsForValue().set(user.getUsername(),newUser);
        return new ResponseMessage(200,"修改密码成功",i);

    }

    @Override
    public ResponseMessage registerUser(String username, String password) {
        if (username.isEmpty()||password.isEmpty()){
            return new ResponseMessage(500,"注册失败");
        }
        userMapper.saveUser(username,password);
        return new ResponseMessage(200,"注册成功");
    }
}
